#include "mainwindow.hpp"
#include "ui_main.h"
#include "fstree.hpp"
#include "filelist.hpp"
#include "devdialog.hpp"
#include "fs.hpp"
#include "contents.hpp"
#include "worddialog.hpp"
#include "searchwindow.hpp"
#include "common.hpp"

MainWindow::MainWindow()
{
	fstree = NULL;
	fl = NULL;
	fs = NULL;
	contents = new Contents(NULL);
	ui = new Ui_MainWindow;
	
	//setup
	ui->setupUi(this);
	ui->fstree->setModel(fstree);
	ui->flist->setModel(fl);
	QHBoxLayout *hbox = new QHBoxLayout(ui->frame);
	hbox->setMargin(0);
	hbox->addWidget(contents);
	ui->frame->setLayout(hbox);
	
	//connect
	QObject::connect(ui->actionDevice, SIGNAL(triggered()), this, SLOT(changeDevice()));
	QObject::connect(ui->actionKeyword, SIGNAL(triggered()), this, SLOT(changeKeyword()));
	QObject::connect(ui->actionSearch, SIGNAL(triggered()), this, SLOT(showSearch()));

	//TODO: remove this, for debug only
	keyword.regexp = "in DOS";
}

MainWindow::~MainWindow()
{
	delete fstree;
	delete fl;
	delete fs;
	delete ui;
}

void MainWindow::changeDevice()
{
	Device buf;
	DeviceDialog dd;
	dd.exec();

	if(dd.result() != QDialog::Accepted){
		return;
	}

	if(!dd.getDevice(buf)){
		return;
	}	

	device = buf;

	//make FS, FileList, fstree
	fs = new FS(buf);
	fl = new FileList(fs);
	fstree = new FSTree(fs);

	//setmodels to views
	ui->flist->setModel(fl);
	ui->fstree->setModel(fstree);
	contents->setFS(fs);

	//connect signals
	QObject::connect(ui->fstree, SIGNAL(activated ( const QModelIndex & )), 
					 fstree, SLOT(toggleItem(const QModelIndex &)));
	QObject::connect(ui->fstree, SIGNAL(doubleClicked ( const QModelIndex & )), 
					 fstree, SLOT(toggleItem(const QModelIndex &)));
	QObject::connect(ui->fstree->selectionModel(), SIGNAL(currentChanged ( const QModelIndex &, const QModelIndex & )), 
					 fl, SLOT(setPath(const QModelIndex &)));
	QObject::connect(ui->fstree->selectionModel(), SIGNAL(currentChanged ( const QModelIndex &, const QModelIndex & )), 
					 ui->flist, SLOT(resizeColumnsToContents()));
	QObject::connect(ui->flist->selectionModel(), SIGNAL(currentChanged (const QModelIndex &, const QModelIndex& )), 
					 contents, SLOT(setFile(const QModelIndex &)));
}

void MainWindow::changeKeyword()
{
	WordDialog wd(keyword);
	wd.exec();
	if(wd.result() == QDialog::Accepted){
		keyword = wd.getKeyword();
	}
}

void MainWindow::showSearch()
{
	QErrorMessage em(this);
	if(!fstree){
		em.showMessage("Please, choose device.");
		em.exec();
		return;
	}

	Task t;
	t.flist = fstree->getSelected();
	t.d = device;
	t.k = keyword;

	//show error messages
	QString error = "";
	if(t.k.regexp.isEmpty())
		error = "Keyword is empty";
	if(t.flist.isEmpty())
		error = "Directory list is empty";
	if(!error.isEmpty()){
		em.showMessage(error);
		em.exec();
		return;
	}
	
	SearchWindow *sw = new SearchWindow(t);
	sw->show();
}
